package com.liaozibo.demo.seckill.web.aop;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class MyRateLimiterAspect {
    private static final RateLimiter rateLimiter = RateLimiter.create(10);

    @Pointcut("@annotation(com.liaozibo.demo.seckill.web.aop.MyRateLimiter)")
    public void pointcut(){}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        boolean success = rateLimiter.tryAcquire();
        if (!success) {
            log.error("被限流了");
            return null;
        }
        Object obj = null;
        try {
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
}
